package servlet.zyb;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.input.SAXBuilder;

public class ShowVoteServlet extends HttpServlet {

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {

		String qName = req.getParameter("name");
		qName = new String(qName.getBytes("ISO-8859-1"), "UTF-8");// 解决乱码
		System.out.println(qName);

		req.getSession().setAttribute("qName", qName);
		req.setCharacterEncoding("UTF-8");

		SAXBuilder builder = new SAXBuilder();
		Document document = null;
		try {
			document = builder.build(new File(
					"E:\\MyeclipseWorkspace\\vote\\question.xml"));
		} catch (JDOMException e) {
			e.printStackTrace();
		}
		Element root = document.getRootElement();// 获取根元素

		List<Element> list = root.getChildren();
		List<String> optionContents = new ArrayList<String>();
		for (int i = 0; i < list.size(); i++) {

			String name = list.get(i).getChild("questionname").getText();
			if (qName != null && qName.equals(name)) {

				List<Element> options = list.get(i).getChild("options")
						.getChildren();
				req.setAttribute("optionNum", options.size());// 把选项数目传递过去

				for (int j = 0; j < options.size(); j++) {

					optionContents.add(options.get(j).getText());
					req.setAttribute("optionContents", optionContents);// 将选项里的内容封装到集合中
																		// 传递过去
				}
			} else {
				continue;
			}
		}

		req.getRequestDispatcher("showVoteMessage.jsp").forward(req, resp);
	}
}
